package edu.nau.its.acad.ole.blackboard.s3dropbox.controller;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Encoder;

public class PolicyDoc {
	private String key;
	private String AWSAccessKeyId;
	private String acl;
	private String success_action_redirect;
	private String policyDoc;
	private String signature;
	private String bucket;
	private String expiration;
	private String policyDocBase64;
	private String courseName;
	private String fullName;
	private String uid;
	
	public void createPolicyDoc() throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
		Date d = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.HOUR, 2);
		d=c.getTime();
		StringBuilder sb = new StringBuilder();
		this.expiration=sdf.format(c.getTime());
		sb.append("{\"expiration\": \"" + this.expiration + "\",");
		sb.append("	  \"conditions\": [ ");
		sb.append("	    {\"bucket\": \"" + this.bucket + "\"}, ");
		sb.append("	    {\"fullname\": \"" + this.fullName + "\"}, ");
		sb.append("	    {\"uid\": \"" + this.uid + "\"}, ");
		sb.append("	    [\"starts-with\", \"$key\", \"" + this.courseName + "\"],");
		sb.append("	    {\"acl\": \"" + this.acl + "\"},");
		sb.append("	    {\"success_action_redirect\": \"" + this.success_action_redirect + "\"},");
		sb.append("	    [\"content-length-range\", 0, 1048576]");
		sb.append("	  ]");
		sb.append("	}");
		this.setPolicyDoc(sb.toString());
		this.policyDocBase64 = (new BASE64Encoder()).encode(
				policyDoc.getBytes("UTF-8")).replaceAll("\n","").replaceAll("\r","");
	}
	public void setupAuth(String aws_secret_key) throws Exception{
		createPolicyDoc();
		Mac hmac = Mac.getInstance("HmacSHA1");
		hmac.init(new SecretKeySpec(
				aws_secret_key.getBytes("UTF-8"), "HmacSHA1"));
		this.signature = (new BASE64Encoder()).encode(
				hmac.doFinal(policyDocBase64.getBytes("UTF-8")))
				.replaceAll("\n", "");
	}
	public static String getDownloadLink(String aws_secret_key, String aws_public_key, String path, int expireMins, String bucket) throws Exception{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
		Date d = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		c.add(Calendar.MINUTE,expireMins);
		d=c.getTime();
		long eTime = (d.getTime())/1000;
		
		String strToSign = "GET\n\n\n"+eTime+"\n/" + bucket + "/" + path;
		
		Mac hmac = Mac.getInstance("HmacSHA1");
		hmac.init(new SecretKeySpec(
				aws_secret_key.getBytes("UTF-8"), "HmacSHA1"));
		String sig = (new BASE64Encoder()).encode(
				hmac.doFinal(strToSign.getBytes("UTF-8")))
				.replaceAll("\n", "");
		sig=URLEncoder.encode(sig);
		return "https://" + bucket + ".s3.amazonaws.com/"+path + "?AWSAccessKeyId=" + aws_public_key + "&Expires=" + eTime + "&Signature=" + sig;
	}
	public String getForm() throws Exception{
		if(this.signature==null)
			throw new Exception("Must run setupAuth(aws_Sec_key) first!!!");
		StringBuilder sb = new StringBuilder();
		sb.append("<form action=\"https://" + this.bucket + ".s3.amazonaws.com/\" method=\"post\" enctype=\"multipart/form-data\">");
		sb.append("  <input type=\"hidden\" name=\"key\" value=\"" + this.courseName + "/${filename}\">");
		sb.append("  <input type=\"hidden\" name=\"AWSAccessKeyId\" value=\"" + this.getAWSAccessKeyId() + "\"> ");
		sb.append("  <input type=\"hidden\" name=\"acl\" value=\"" + this.getAcl() + "\"> ");
		sb.append("  <input type=\"hidden\" name=\"success_action_redirect\" value=\"" + this.getSuccess_action_redirect() + "\">");
		sb.append("  <input type=\"hidden\" name=\"uid\" value=\"" + this.uid + "\">");
		sb.append("  <input type=\"hidden\" name=\"fullname\" value=\"" + this.fullName + "\">");
		sb.append("   <input type=\"hidden\" name=\"policy\" value=\"" + this.policyDocBase64 + "\">");
		sb.append("  <input type=\"hidden\" name=\"signature\" value=\"" + this.getSignature() + "\">");
		sb.append("   <!-- Include any additional input fields here -->");
		sb.append("");
		sb.append("   File to upload: ");
		sb.append("   <input name=\"file\" type=\"file\"> ");
		sb.append("   <br> ");
		sb.append("   <input type=\"submit\" value=\"Upload File\"> ");
		sb.append(" </form> ");
		return sb.toString();
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	public String getAWSAccessKeyId() {
		return AWSAccessKeyId;
	}
	public void setAWSAccessKeyId(String aWSAccessKeyId) {
		AWSAccessKeyId = aWSAccessKeyId;
	}
	public String getAcl() {
		return acl;
	}
	public void setAcl(String acl) {
		this.acl = acl;
	}
	public String getSuccess_action_redirect() {
		return success_action_redirect;
	}
	public void setSuccess_action_redirect(String success_action_redirect) {
		this.success_action_redirect = success_action_redirect;
	}
	public String getPolicyDoc() {
		return policyDoc;
	}
	public void setPolicyDoc(String policyDoc) {
		this.policyDoc = policyDoc;
	}
	public String getSignature() {
		return signature;
	}
	public void setSignature(String signature) {
		this.signature = signature;
	}
	public String getBucket() {
		return bucket;
	}
	public void setBucket(String bucket) {
		this.bucket = bucket;
	}
	public String getCourseName() {
		return courseName;
	}
	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}
	public String getFullName() {
		return fullName;
	}
	public void setFullName(String fullName) {
		this.fullName = fullName;
	}
	public String getUid() {
		return uid;
	}
	public void setUid(String uid) {
		this.uid = uid;
	}
	
	
}
